package com.personal.dao.sqlgenerator;

import java.util.ArrayList;
import java.util.List;

import com.personal.dao.bean.BaseModel;
import com.personal.dao.configuration.Configuration;
import com.personal.dao.exception.NoPrimaryKeyException;
import com.personal.dao.metadata.DataBaseFieldMetadata;
import com.personal.dao.metadata.DataBasePrimaryKeyMetadata;
import com.personal.dao.metadata.DataBaseTableMetadata;
import com.personal.dao.reflection.MetaObject;
import com.personal.dao.sql.BaseBatchSql;
import com.personal.dao.sql.BatchSql;

/**
 * 批量插入
 * @author cuibo
 *
 */
public class BatchInsert<T extends BaseModel> extends BaseBatchSqlGenerator<T>
{

    public BatchInsert(List<T> records, DataBaseTableMetadata<T> metadata)
    {
        super(records, metadata);
    }

    @Override
    public BatchSql generate()
    {
        List<Object[]> datas = new ArrayList<Object[]>(records.size());
        StringBuilder before = new StringBuilder("insert into ").append(metadata.getTableName()).append(" (");
        StringBuilder after = new StringBuilder();
        int index = -1;
        for (T t : records)
        {
        	MetaObject metaObject = Configuration.getInstance().newMetaObject(t);
        	// 校验
        	SqlValidator.validate(metadata, t, metaObject);
            index ++;
            List<Object> list = new ArrayList<>(metadata.getFields().size() + 1);
            
            DataBasePrimaryKeyMetadata primaryKey = metadata.getPrimaryKey();
            if (primaryKey != null)
            {
                if (index == 0)
                {
                    before.append(primaryKey.getColumnName()).append(",");
                    after.append("?,");
                }
                Object value = metaObject.getValue(primaryKey.getFieldName()); 
            	if (value == null)
    			{
            		// 考虑自动生成
                	if (primaryKey.getGenerator() != null)
        			{
                		value = primaryKey.getGenerator().generatorPrimaryKey();
                		metaObject.setValue(primaryKey.getFieldName(), value);
        			}
                	if (value == null)
					{
                		throw new NoPrimaryKeyException(t + "的主键不能为空！");
					}
    			}	
                list.add(value);
            }
            for (DataBaseFieldMetadata field : metadata.getFields())
            {
                if (index == 0)
                {
                    before.append(field.getColumnName()).append(",");
                    after.append("?,");
                }
                Object value = metaObject.getValue(field.getFieldName());
                list.add(value);
            }
            if (index == 0)
            {
                before.deleteCharAt(before.length() - 1).append(")").append(" values (");
                before.append(after.deleteCharAt(after.length() - 1)).append(")");
            }
            datas.add(list.toArray(new Object[list.size()]));
        }
        
        return new BaseBatchSql(before.toString(), datas);
    }

}
